﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Threading;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using System.ComponentModel;
using Microsoft.Advertising.Mobile.UI;
using Microsoft.Phone.Net.NetworkInformation;
using Microsoft.Phone.Shell;
using OnlineVideos.RingToneEditor;
using OnlineVideos.Entities;
using OnlineVideos.Common;
using OnlineVideos.UI;
using Common.Library;
using Common.Utilities;
using System.Threading.Tasks;



namespace OnlineVideos.Views
{
    public partial class RingTone : PhoneApplicationPage
    {
        #region GlobalDeclaration
        BackgroundHelper bwHelper = new BackgroundHelper();
        static Stream DownloadStream;
        SaveRingtoneTask saveRingtoneChooser;
        bool IsPreviewMode = false;
        #endregion

        #region Constructor
        public RingTone()
        {
            InitializeComponent();  
            Loaded += new RoutedEventHandler(RingTone_Loaded);
        }
        #endregion

        #region PageLoad
        void RingTone_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.LogEvent("RingTone Page", true);
           
           
            if (NetworkInterface.GetIsNetworkAvailable() && NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None)
            {
             
                txterror.Visibility = Visibility.Collapsed;
             performanceProgressBar.IsIndeterminate = true;
             if (!AppSettings.ShowLinkTitle.ToLower().StartsWith("http://"))
             {
                 if (AppSettings.ShowLinkTitle.ToLower().Contains("www."))
                     AppSettings.ShowLinkTitle = "http://" + AppSettings.ShowLinkTitle;
                 else
                     AppSettings.ShowLinkTitle = "http://www." + AppSettings.ShowLinkTitle;
             }
                WebClient web = new WebClient();
                web.OpenReadAsync(new Uri(AppSettings.ShowLinkTitle, UriKind.Absolute));
                web.OpenReadCompleted += new OpenReadCompletedEventHandler(web_OpenReadCompleted);
            }
            else
            {
                ApplicationBar.IsVisible = false;
                ErrorMessage(Constants.NetworkErrorMessageForRingTone, Visibility.Visible);
            }
            }
            catch (Exception ex)
            {

               Exceptions.SaveOrSendExceptions("Exception in RingTone_Loaded Method In RingTone.cs file.", ex);
        }

        }
        #endregion

        #region "Common Methods"
       

        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, adstaRing, 1);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }

     
        object LoadImage(string path)
        {
            object objImage = null;
            BitmapImage bi = new BitmapImage();
            bi.UriSource = new Uri(path, UriKind.Relative);
            objImage = bi;
            return objImage;
        }
              
        void TrimCompleted()
        {
            float fileSize = Storage.GetFileSize(ResourceHelper.RingToneFileName(AppSettings.Chapterno), FileSizeUnit.MB);

            //RingTone should not be greater than 1MB
            if (fileSize > 1)
            {
                ErrorMessage(Constants.SongSizeErrorMessage, Visibility.Collapsed);
                if (Task.Run(async()=> await Storage.FileExists(ResourceHelper.RingToneFileName(AppSettings.Chapterno))).Result)
                    Storage.DeleteFile(ResourceHelper.RingToneFileName(AppSettings.Chapterno));
            }
            else
            {
                txtfilesize.Text = fileSize.ToString("N2") + " MB";
                txtfilesize.Visibility = Visibility.Visible;
            }
        }
        public void ErrorMessage(string message, Visibility visible)
        {
            txterror.Text = message;
            txterror.Visibility = visible;
        }
        void TrimForRingTone()
        {
            IsolatedStorageFileStream local = Storage.CreateFile(ResourceHelper.RingToneFileName(AppSettings.Chapterno).Substring(ResourceHelper.RingToneFileName(AppSettings.Chapterno).IndexOf('/') + 1));
            using (var reader = new Mp3FileReader(DownloadStream))
            {
                Mp3Frame frame = new Mp3Frame();
                while ((frame = reader.ReadNextFrame()) != null)
                {
                    if ((int)reader.CurrentTime.TotalSeconds <= Convert.ToDouble(tbend.Text) && (int)reader.CurrentTime.TotalSeconds >= Convert.ToDouble(tbbegin.Text))
                        local.Write(frame.RawData, 0, frame.RawData.Length);
                }
                local.Close();
                local.Dispose();
            }


        }
        void songReady()
        {

            playimage.Source = LoadImage(Constants.PlayerPlayImage) as ImageSource;
            ControlVisibility(Visibility.Visible);
            txtTitle.Text = AppSettings.Chapterno;
        }
        private void Playsong()
        {
            mymedia.Play();
            playimage.Source = LoadImage(Constants.PlayerPauseImage) as ImageSource;
        }
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.EndTimedEvent("RingTone Page");
            var backkey = NavigationService.BackStack.ToList();
            foreach (var itm in backkey)
            {
                if (itm.Source.ToString().Contains(AppResources.DetailPageName) || itm.Source.ToString().Contains("RingTone.xaml"))
                {
                    NavigationService.RemoveBackEntry();
                }
            }
        }
            catch (Exception ex)
            {
                
            Exceptions.SaveOrSendExceptions("Exception in OnNavigatedFrom Method In RingTone.cs file.", ex);
            }
        }
        public void ControlVisibility(Visibility visible)
        {
            foreach (UIElement c in Playergrid.Children)
            {
                Type type = c.GetType();
                if (type.Name == "TextBox")
                {
                    TextBox t = c as TextBox;
                    if (t.Name != "txterror" && t.Name != "txtfilesize")
                        t.Visibility = visible;
                }
                else
                {
                    c.Visibility = visible;
                }
            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.LogPageView();
            if (PhoneApplicationService.Current.State.Keys.Contains("RingtoneStatus"))
            {
                if (AppState.RingtoneStatus == "TombStoned" || AppState.RingtoneStatus == "RingToneTask")
                {
                    AppState.RingtoneStatus = "";
                   
                        NavigationService.Navigate(new Uri("/Views/" + AppResources.DetailPageName + ".xaml", UriKind.Relative));
                }
                else
                {
                   
                    txtfilesize.Visibility = Visibility.Collapsed;
                    txterror.Visibility = Visibility.Collapsed;
                    ControlVisibility(Visibility.Collapsed);
                }
            }
            else
            {

                txtfilesize.Visibility = Visibility.Collapsed;
                txterror.Visibility = Visibility.Collapsed;
                ControlVisibility(Visibility.Collapsed);
            }
        }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo Method In RingTone.cs file.", ex);
            }
        }
        void UpdateSlider(object sender, EventArgs e)
        {
            try
            {
            ringtoneslider.updatesliderValue(mymedia.Position);
        }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in UpdateSlider Method In RingTone.cs file.", ex);
            }
        }
        void Rewind(object sender, EventArgs e)
        {
            mymedia.Pause();
            int SliderValue = (int)ringtoneslider.getsliderValue();
            TimeSpan ts = new TimeSpan(0, 0, 0, SliderValue - 3, 0);
            mymedia.Position = ts;
        }
        private void TrimSongForRingTone()
        {
            if (IsPreviewMode == false)
            {
                string Range = string.Empty;
                tbend.Text = mymedia.Position.TotalSeconds.ToString();
                if (tbbegin.Text != "")
                {
                    if (Convert.ToDouble(tbbegin.Text) < Convert.ToDouble(tbend.Text) && tbbegin.Text != "" && tbend.Text != "")
                    {
                        txterror.Visibility = Visibility.Collapsed;
                        Range = (Convert.ToDouble(tbend.Text) - Convert.ToDouble(tbbegin.Text)).ToString();

                        if (Convert.ToDouble(Range) <= 40)
                        {
                            bwHelper.AddBackgroundTask(
                                       (object s, DoWorkEventArgs a) =>
                                       {
                                           Deployment.Current.Dispatcher.BeginInvoke(() =>
                                           {
                                               TrimForRingTone();
                                           });
                                       },
                                       (object s, RunWorkerCompletedEventArgs a) =>
                                       {
                                           TrimCompleted();
                                       }
                                     );
                            bwHelper.RunBackgroundWorkers();
                            txttimerange.Text = Range + " secs";
                        }

                        else
                        {
                            ErrorMessage(Constants.SongDurationErrorMessageForRingTone, Visibility.Visible);
                        }
                    }
                }
                else
                {
                    ErrorMessage(Constants.BeginTimeErrorMessageForRingTone, Visibility.Visible);

                }
            }
            else
            {
                ErrorMessage(Constants.PreviewModeErrorMessageForRingTone, Visibility.Visible);
            }
        }
        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            mymedia.Source = null;
            if (Task.Run(async()=> await Storage.FileExists(ResourceHelper.RingToneFileName(AppSettings.Chapterno))).Result)
                Storage.DeleteFile(ResourceHelper.RingToneFileName(AppSettings.Chapterno));
            AppState.RingtoneStatus = "";
            // e.Cancel = true;
            //PageHelper.NavigateToDetailPage(AppResources.DetailPageName, AppSettings.ShowID);
        }
        void forward(object sender, EventArgs e)
        {
            mymedia.Pause();
            int SliderValue = (int)ringtoneslider.getsliderValue();
            TimeSpan ts = new TimeSpan(0, 0, 0, SliderValue + 3, 0);
            mymedia.Position = ts;
        }
        #endregion

        #region Events
        private void playimage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            BitmapImage bi = new BitmapImage();
            bi = playimage.Source as BitmapImage;
            if (bi.UriSource.ToString().Contains("play.png"))
            {
                Playsong();
                playimage.Source = LoadImage(Constants.PlayerPauseImage) as ImageSource;
            }
            else
            {
                mymedia.Pause();
                playimage.Source = LoadImage(Constants.PlayerPlayImage) as ImageSource;
            }
        }
        void web_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
            if (e.Error == null)
            {
                DownloadStream = e.Result;
                songReady();
                mymedia.Source = new Uri(AppSettings.ShowLinkTitle, UriKind.Absolute);
                playimage.Source = LoadImage(Constants.PlayerPauseImage) as ImageSource;
                ringtoneloadingmessage.Visibility = Visibility.Collapsed;
                performanceProgressBar.IsIndeterminate = false;
            }
            else
            {
                ErrorMessage(Constants.NetworkErrorMessageForRingTone, Visibility.Visible);
            }
        }
            catch (Exception ex)
            {
                
                  Exceptions.SaveOrSendExceptions("Exception in web_OpenReadCompleted Method In RingTone.cs file.", ex);
            }
        }
        void saveRingtoneChooser_Completed(object sender, TaskEventArgs e)
        {
            if (Task.Run(async()=> await Storage.FileExists(ResourceHelper.RingToneFileName(AppSettings.Chapterno))).Result)
            {
                try
                {

                    switch (e.TaskResult)
                    {

                        case TaskResult.OK:
                            MessageBox.Show("Ringtone saved.");
                            break;


                        case TaskResult.Cancel:
                            MessageBox.Show("Save cancelled.");
                            break;


                        case TaskResult.None:
                            MessageBox.Show("Ringtone could not be saved.");
                            break;
                    }

                    if (Task.Run(async()=> await Storage.FileExists(ResourceHelper.RingToneFileName(AppSettings.Chapterno))).Result)
                        Storage.DeleteFile(ResourceHelper.RingToneFileName(AppSettings.Chapterno));

                }
                catch (System.InvalidOperationException ex)
                {
                    MessageBox.Show("An error occurred.");
                    Exceptions.SaveOrSendExceptions("Exception in saveRingtoneChooser_Completed Method In RingTone.cs file.", ex);
                }
            }
           

        }
        private void btnbegin_Click(object sender, RoutedEventArgs e)
        {
            try
            {
            if (IsPreviewMode == false)
            {
                txterror.Visibility = Visibility.Collapsed;
                tbbegin.Text = mymedia.Position.TotalSeconds.ToString();
                tbend.Text = "";
            }
            else
            {
                ErrorMessage(Constants.PreviewModeErrorMessageForRingTone, Visibility.Visible);
            }
        }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in btnbegin_Click Method In RingTone.cs file.", ex);
            }
        }
        private void btnend_Click(object sender, RoutedEventArgs e)
        {
            try
            {
            TrimSongForRingTone();
        }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in btnend_Click Method In RingTone.cs file.", ex);
            }
        }
        private void forwardimage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
            bwHelper.AddScheduledBackgroundTask(forward, TimeSpan.FromMilliseconds(5), 2);
            bwHelper.StartScheduledTasks(2);
        }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in forwardimage_MouseLeftButtonDown Method In RingTone.cs file.", ex);
            }
        }
        private void mymedia_MediaOpened(object sender, RoutedEventArgs e)
        {
            try
            {
            var value = mymedia.NaturalDuration.TimeSpan.TotalSeconds;
            ringtoneslider.setmaxsliderValue(value);
            mymedia.AutoPlay = false;
            bwHelper.AddScheduledBackgroundTask(UpdateSlider, TimeSpan.FromSeconds(1), 0);
            bwHelper.StartScheduledTasks(0);
        }
            catch (Exception ex)
            {
                
                   Exceptions.SaveOrSendExceptions("Exception in mymedia_MediaOpened Method In RingTone.cs file.", ex);
            }
        }
        private void Rewindimage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
            bwHelper.AddScheduledBackgroundTask(Rewind, TimeSpan.FromMilliseconds(5), 1);
            bwHelper.StartScheduledTasks(1);
        }
            catch (Exception ex)
            {
                
                  Exceptions.SaveOrSendExceptions("Exception in Rewindimage_MouseLeftButtonDown Method In RingTone.cs file.", ex);
            }
        }
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (Task.Run(async () => await Storage.FileExists(ResourceHelper.RingToneFileName(AppSettings.Chapterno))).Result)
            {
                AppState.RingtoneStatus = "RingToneTask";
                saveRingtoneChooser = new SaveRingtoneTask();
                saveRingtoneChooser.Source = new Uri("isostore:" + ResourceHelper.RingToneFileName(AppSettings.Chapterno));
                saveRingtoneChooser.DisplayName = AppSettings.Chapterno;
                saveRingtoneChooser.Show();
                saveRingtoneChooser.Completed += new EventHandler<TaskEventArgs>(saveRingtoneChooser_Completed);
             
            }
            else
            {
                ErrorMessage(Constants.TimeErrorMessageForSaveRingTone, Visibility.Visible);
            }
        }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in ApplicationBarIconButton_Click Method In RingTone.cs file.", ex);
            }
        }
        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            try
            {
            mymedia.Source = null;
                if (Task.Run(async () => await Storage.FileExists(ResourceHelper.RingToneFileName(AppSettings.Chapterno))).Result)
                Storage.DeleteFile(ResourceHelper.RingToneFileName(AppSettings.Chapterno));
            AppState.RingtoneStatus = "";
            
                NavigationService.Navigate(new Uri("/Views/" + AppResources.DetailPageName + ".xaml?id=" + AppSettings.ShowID, UriKind.Relative));
            }
            catch (Exception ex)
            {
                
             Exceptions.SaveOrSendExceptions("Exception in ApplicationBarIconButton_Click_1 Method In RingTone.cs file.", ex);
            }
        }
        private void mymedia_MediaEnded(object sender, RoutedEventArgs e)
        {
            try
            {
            playimage.Source = LoadImage(Constants.PlayerPlayImage) as ImageSource;
            IsPreviewMode = false;
            mymedia.Source = new Uri(AppSettings.ShowLinkTitle, UriKind.Absolute);
        }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in mymedia_MediaEnded Method In RingTone.cs file.", ex);
            }
        }
        private void btnPreview_Click(object sender, EventArgs e)
        {
            try
            {
                if (Task.Run(async () => await Storage.FileExists(ResourceHelper.RingToneFileName(AppSettings.Chapterno))).Result)
            {
                IsPreviewMode = true;
                txterror.Visibility = Visibility.Collapsed;
                mymedia.Stop();
                BitmapImage bi = new BitmapImage();
                bi = playimage.Source as BitmapImage;
                if (bi.UriSource.ToString().Contains("pause.png"))
                {
                    playimage.Source = LoadImage(Constants.PlayerPlayImage) as ImageSource;
                }
                using (IsolatedStorageFileStream fs = Storage.OpenFile(ResourceHelper.RingToneFileName(AppSettings.Chapterno), FileMode.Open, FileAccess.Read))
                {
                    mymedia.SetSource(fs);
                }

                mymedia.AutoPlay = true;
                playimage.Source = LoadImage(Constants.PlayerPauseImage) as ImageSource;

            }
            else
            {
                ErrorMessage(Constants.TimeErrorMessageForRingTone, Visibility.Visible);
            }
        }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in btnPreview_Click Method In RingTone.cs file.", ex);
            }
        }
        private void ringtoneslider_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            try
            {
            bwHelper.StopScheduledTasks(0);
        }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in ringtoneslider_ManipulationStarted Method In RingTone.cs file.", ex);
            }
        }
        private void ringtoneslider_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
            try
            {
            int SliderValue = (int)ringtoneslider.getsliderValue();
            TimeSpan ts = new TimeSpan(0, 0, 0, SliderValue, 0);
            mymedia.Position = ts;
            bwHelper.StartScheduledTasks(0);
        }
            catch (Exception ex)
            {
                
              Exceptions.SaveOrSendExceptions("Exception in ringtoneslider_ManipulationCompleted Method In RingTone.cs file.", ex);
            }
        }
        private void tbend_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
            TrimSongForRingTone();
        }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in tbend_LostFocus Method In RingTone.cs file.", ex);
            }
        }
        private void tbbegin_LostFocus(object sender, RoutedEventArgs e)
        {
            if (IsPreviewMode == false)
            {
                txterror.Visibility = Visibility.Collapsed;
            }
            else
            {
                ErrorMessage(Constants.PreviewModeErrorMessageForRingTone, Visibility.Visible);
            }
        }
        private void Rewindimage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
            bwHelper.StopScheduledTasks(1);
            mymedia.Play();
        }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in Rewindimage_MouseLeftButtonUp Method In RingTone.cs file.", ex);
            }
        }
        private void forwardimage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
            bwHelper.StopScheduledTasks(2);
            mymedia.Play();
        }
            catch (Exception ex)
            {
                
                  Exceptions.SaveOrSendExceptions("Exception in forwardimage_MouseLeftButtonUp Method In RingTone.cs file.", ex);
            }
        }
        private void imgTitle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(NavigationHelper.MainPanoramaPage);
        }
        #endregion

    }
}